<template>
  <div class="map-container">
    <div id="map" ref="mapContainer"></div>
    <div class="control-panel">
      <button @click="togglePolygons">{{ showPolygons ? '隐藏面' : '显示面' }}</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
import { setMapInstance } from '@/utils/mapUtils'

const mapContainer = ref<HTMLElement | null>(null)
let map: mapboxgl.Map | null = null
const showPolygons = ref(false)

// 示例多边形数据
const polygons = {
  'type': 'FeatureCollection',
  'features': [
    {
      'type': 'Feature',
      'properties': {
        'name': '区域1',
        'description': '这是第一个区域'
      },
      'geometry': {
        'type': 'Polygon',
        'coordinates': [[
          [116.387428, 39.90923],
          [116.397428, 39.91923],
          [116.399428, 39.90923],
          [116.397428, 39.89923],
          [116.387428, 39.90923]
        ]]
      }
    },
    {
      'type': 'Feature',
      'properties': {
        'name': '区域2',
        'description': '这是第二个区域'
      },
      'geometry': {
        'type': 'Polygon',
        'coordinates': [[
          [116.407428, 39.90923],
          [116.417428, 39.91923],
          [116.427428, 39.90923],
          [116.417428, 39.89923],
          [116.407428, 39.90923]
        ]]
      }
    }
  ]
}

const initMap = () => {
  if (!mapContainer.value) return
  
  mapboxgl.accessToken = import.meta.env.VITE_APP_MAP_TOKEN
  
  map = new mapboxgl.Map({
    container: mapContainer.value,
    style: 'mapbox://styles/mapbox/streets-v12',
    center: [116.397428, 39.90923],
    zoom: 12
  })

  map.on('load', () => {
    // 添加数据源
    map?.addSource('polygons', {
      type: 'geojson',
      data: polygons as GeoJSON.FeatureCollection
    })

    // 添加填充图层
    map?.addLayer({
      id: 'polygons-fill-layer',
      type: 'fill',
      source: 'polygons',
      paint: {
        'fill-color': '#4CAF50',
        'fill-opacity': 0.4
      },
      layout: {
        'visibility': 'none'
      }
    })

    // 添加边界线图层
    map?.addLayer({
      id: 'polygons-outline-layer',
      type: 'line',
      source: 'polygons',
      paint: {
        'line-color': '#4CAF50',
        'line-width': 2,
        'line-opacity': 0.8
      },
      layout: {
        'visibility': 'none'
      }
    })

    // 添加标注图层
    map?.addLayer({
      id: 'polygons-label',
      type: 'symbol',
      source: 'polygons',
      layout: {
        'visibility': 'none',
        'text-field': ['get', 'name'],
        'text-size': 12,
        'text-anchor': 'center'
      },
      paint: {
        'text-color': '#000000',
        'text-halo-color': '#ffffff',
        'text-halo-width': 2
      }
    })

    // 添加鼠标悬停效果
    map?.on('mousemove', 'polygons-fill-layer', (e) => {
      if (e.features && e.features.length > 0) {
        map!.getCanvas().style.cursor = 'pointer'
        
        // 高亮显示悬停的多边形
        if (map?.getLayer('hover-polygon')) {
          const feature = e.features[0]
          map?.setFilter('hover-polygon', ['==', ['get', 'name'], feature?.properties?.name])
        }
      }
    })

    map?.on('mouseleave', 'polygons-fill-layer', () => {
      map!.getCanvas().style.cursor = ''
      if (map?.getLayer('hover-polygon')) {
        map?.setFilter('hover-polygon', ['==', 'name', ''])
      }
    })

    // 添加悬停高亮图层
    map?.addLayer({
      id: 'hover-polygon',
      type: 'fill',
      source: 'polygons',
      paint: {
        'fill-color': '#4CAF50',
        'fill-opacity': 0.6
      },
      filter: ['==', 'name', '']
    })

    // 添加鼠标点击事件以显示信息框
    map?.on('click', 'polygons-fill-layer', (e) => {
      if (e.features && e.features.length > 0) {
        const feature = e.features[0]

        const coordinates = e.lngLat // 使用鼠标点击的经纬度

        const description = `
          <h3>${feature.properties?.name || '未知区域'}</h3>
          <p>${feature.properties?.description || '无描述信息'}</p>
        `
        console.log(e, coordinates);
        
        // 创建并显示信息框
        new mapboxgl.Popup()
          // .setLngLat(coordinates)
          .setLngLat([e.lngLat.lng, e.lngLat.lat])
          .setHTML(description)
          .addTo(map!)
      }
    })
  })

  setMapInstance(map)
}

const togglePolygons = () => {
  showPolygons.value = !showPolygons.value
  const visibility = showPolygons.value ? 'visible' : 'none'
  
  if (map?.getLayer('polygons-fill-layer')) {
    map?.setLayoutProperty('polygons-fill-layer', 'visibility', visibility)
    map?.setLayoutProperty('polygons-outline-layer', 'visibility', visibility)
    map?.setLayoutProperty('polygons-label', 'visibility', visibility)
  }
}

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  map?.remove()
  map = null
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
}

.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1;
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

button {
  padding: 8px 16px;
  background: #2c3e50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background: #34495e;
}
</style> 